package org.example.demo.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.demo.entity.Promotion;
import org.example.demo.service.PromotionService;
import org.example.demo.util.AjaxResult;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 晋升记录控制器
 */
@RestController
@RequestMapping("promotion")
public class PromotionController {

    @Resource
    private PromotionService promotionService;

    /**
     * 分页查询晋升记录
     *
     * @param promotion 查询条件
     * @param pageNum   页码
     * @param pageSize  每页大小
     * @return 查询结果
     */
    @PostMapping("page")
    public AjaxResult page(@RequestBody Promotion promotion,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Promotion> page = promotionService.selectPage(promotion, pageNum, pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("page", page);
        result.put("total", page.getTotal());

        return AjaxResult.success(result);
    }

    /**
     * 根据ID查询晋升记录
     *
     * @param id 晋升记录ID
     * @return 查询结果
     */
    @GetMapping("{id}")
    public AjaxResult getById(@PathVariable Long id) {
        Promotion promotion = promotionService.getById(id);

        if (promotion != null) {
            return AjaxResult.success(promotion);
        } else {
            return AjaxResult.error("晋升记录不存在");
        }
    }

    /**
     * 新增晋升记录
     *
     * @param promotion 晋升记录信息
     * @return 操作结果
     */
    @PostMapping
    public AjaxResult add(@RequestBody Promotion promotion) {
        if (promotionService.save(promotion)) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("新增失败");
        }
    }

    /**
     * 修改晋升记录
     *
     * @param promotion 晋升记录信息
     * @return 操作结果
     */
    @PutMapping
    public AjaxResult update(@RequestBody Promotion promotion) {
        if (promotionService.updateById(promotion)) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 删除晋升记录
     *
     * @param id 晋升记录ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        if (promotionService.removeById(id)) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    /**
     * 根据userId查询promotions
     * @return
     */
    @GetMapping("/getByUserId/{id}")
    public AjaxResult getByUserId(@PathVariable Long id) {


        List<Promotion> promotions = promotionService.getByUserId(id);

        return AjaxResult.success(promotions);
    }




}